<?php 

class PurchaseController extends Uuch_BaseController {

    public function indexAction() {
        $this->appendCss('/css/daigou/daigou.css');
        $this->appendScript('/js/jquery.min.js');
        $this->setTitle('身在海外，随心购遍国货');
    }

    /**
     * 从商品网址中间提取ID
     * @param type $url
     * @return type 
     */
    public function getId($url) {
        $id = '';
        $queryId = array('id', 'mallstItemId');

        foreach ($queryId as $query) {
            $id = $this->query($url, $query);
            if ($id != NULL)
                break;;
        }

        return $id;
    }

    /**
     * 返回URL中的QueryString的值
     * @param type $url
     * @param type $name
     * @return string 
     */
    protected function query($url, $name) {
        $uri = parse_url($url);
        $query = explode('&', $uri['query']);
        $map = array();
        foreach ($query as $key) {
            $str = explode('=', $key);
            if (count($str) > 1)
                $map[$str[0]] = $str[1];
            else
                $map[$str[0]] = '';
        }
        if (array_key_exists($name, $map))
            return $map[$name];
        else
            return NULL;
    }

    /**
     * 代购
     */
    public function agentAction() {
        $this->appendCss('/css/daigou/fill.css');
        $this->appendScript('/js/jquery.min.js')->appendScript('/js/jquery.validate.min.js')
                ->appendScript('/js/messages_cn.js')->appendScript('/js/famous.js');

	$url = $this->_getParam('url');        
        $regex = '/yhd.com/i';
        $matches = array();
        if(preg_match($regex, $url, $matches)){
            $url = preg_replace("/[\[\]\|`]/si","",$url);
        }
		$uri = parse_url($url);		 
		if(isset($uri['host']) && preg_match('{(.*\.m\.)(.*)}', $uri['host'], $arr)){
			$urlitemid = $this->getId($url);
			 if ($arr[2] == 'taobao.com') {
				$url = 'http://item.taobao.com/item.htm?id=' . $urlitemid; 
			 }
			 if ($arr[2] == 'tmall.com') {
				$url = 'http://detail.tmall.com/item.htm?id=' . $urlitemid; 
			 }
		 }				
        $this->view->url = $url;
        
        $form = new Application_Form_PurchaseAgent();
        $request = $this->getRequest();

        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                if ($request->getPost()) {
                    $sku = $form->getValue('sku');
                    if ($sku == null)
                        $sku = $form->getValue('url'); 

                    $values = $form->getValues();
                    $product = Application_Model_Product::getByUrl($this->_getParam('url'));
                    if (null == $product)
                        $product = new Application_Model_Product();           
                    
                    if($product->Sku != $sku){
                        $product->Id = NULL;
                        $product->Image = $form->getValue('image');
                    }
                    $product->setOptions($values);
                    
                    $product->RemoteImage = $form->getValue('image');
                    $product->ShipFee = $form->getValue('shipFee');
                    $product->Sku = $sku;
                    $product->PropertyAlias = $this->getSafeParam('prop');
                    $product->save();
                    
                    $comm =$this->getSafeParam('comment');
                    $cart = Application_Model_Cart::current();
                    $cart->addCartItem($product, $form->getValue('quantity'), $comm);
                    
                    $this->_helper->redirector('cart');
                }
            }
        }
        $this->view->form = $form;
        $this->view->title = '代购服务';
    }

    /**
     * 购物车
     */
    public function cartAction() {
        $this->appendCss('/css/daigou/fill.css');
        $this->appendScript('/js/jquery.min.js');
        $this->view->cart = Application_Model_Cart::current();
        $userId = 0;
        $this->view->coupons = false;
        if($this->currentUser()){
            $couponSearch = new Application_Model_Filter_CouponSearch();
            $couponSearch->userId = $this->currentUser()->Id;
            $couponSearch->status = Application_Model_Coupon::STATUS_OK;
            $couponSearch->useScope = Application_Model_Coupon::Scope_Order;
            $this->view->coupons = Application_Model_Coupon::getByUser($couponSearch);
            $userId = $this->currentUser()->Id;
        }
        $this->view->userId = $userId;
        $this->view->title = '购物车';
    }

    /**
     * 删除一个购物车中的产品
     */
    public function deleteAction() {
        $id = $this->getRequest()->getParam('id');
        $userId = $this->currentUser()->Id;
        $cartItem = new Application_Model_CartItem($id);
        //删除记录到临时表
        Application_Model_TemporaryCart::addTemporaryLog($cartItem->CartId, $cartItem->Id, $cartItem->ProductName, $cartItem->quantity, Application_Model_TemporaryCart::Type_Delete, $userId);
        $cartItem->delete();
        $this->_helper->redirector('cart');
    }

    /**
     * 删除购物车中 选中的商品
     */
    public function dellistAction(){
        $idList = $this->getSafeParam("idList");
        $userId = $this->currentUser()->Id;
        $list = substr($idList,0,strlen($idList)-1);
        $res = explode(",",$list);
        foreach($res as $val){
            $cartItem = Application_Model_CartItem::load($val);
            //删除记录到临时表
            Application_Model_TemporaryCart::addTemporaryLog($cartItem->CartId, $cartItem->Id, $cartItem->ProductName, $cartItem->quantity, Application_Model_TemporaryCart::Type_Delete, $userId);
            $cartItem->delete();
        }
        $this->json(1);
    }
    
    /**
     * 验证优惠券
     */
    public function validatecouponAction() {
        $no = $this->getSafeParam('couponno');
        $sumMoney = $this->getSafeParam('sumMoney');
        $userid = $this->currentUser()->Id;
        $password = $this->getSafeParam('password');

        $coupon = Application_Model_Coupon::getByNo($no);
        $result = $coupon->Validate($userid, $sumMoney, $password,0);
        $this->json($result);
    }
    
    /**
     * 结算页
     */
    public function checkoutAction() {
        $this->appendCss('/css/daigou/fill.css');
        $this->appendScript('/js/jquery.min.js');
        $this->setTitle('核对订单信息');
        $this->checkLogin();
        if ($this->getRequest()->isPost()) {
            $cart = Application_Model_Cart::current();
            $couponArr = array();
            foreach ($cart->getShops(true) as $shop) {
                $couponNo = $this->_getParam("couponno".$shop->Id);
                $password = $this->_getParam("password".$shop->Id);
                $couponArr[$shop->Id]["couponNo"] = $couponNo[0];
                $couponArr[$shop->Id]["password"] = $password[0];
            }
            $result = $cart->createOrders($couponArr);
            $userId = $this->currentUser()->Id;
            $ids='';
            foreach ($result as $key => $resultVal){
                $order = $resultVal["order"];
                $order->UserId = $userId;
                $order->save();
                $ids= $ids.$order->Id.',';
                if($resultVal["coupon"]){
                    $coupon = $resultVal["coupon"];
                    $coupon->Relevance = $order->Id;
                    $coupon->UseTime = $this->now();
                    $coupon->save();
                }
            }
            $countOrder = Application_Model_Order::getCountByUserId($userId);
            if($countOrder == 1){
                $accountItem = Application_Model_UserAccount::addAccount($userId);
                $accountItem->TaskExchangeScore(Application_Model_Task::TASK_ORDER);
            }
            $ids = substr($ids, 0,  strlen($ids)-1);
            $cart->clear();
            $this->_helper->redirector('paying', "Pay", null, array('id' =>$ids, 'type' => 2));
        }
        $this->appendCss('/css/daigou/fill.css');
        $this->view->cart = Application_Model_Cart::current(TRUE);
    }    
    
    /**
     * 订单生成后的展示页
     */
    public function orderAction() {
        $this->appendCss('/css/daigou/fill.css');
        $this->title = '订单与生成';
        $this->view->order = new Application_Model_Order($this->getRequest()->getParam('id'));
    }

    /**
     * 采集商品信息ddd
     */
    public function getinfoAction() {
        
        $url = $this->getRequest()->getParam('url');
        //echo APPLICATION_PATH.'/models/readers/ProductReader.php';
        $url = trim($url);
        $reader = Uuch_Reader_ProductReader::Create($url);
        $product = $reader->getInfo($url);
        $info = new stdClass();

        if ($product == NULL) {
            $info->success = FALSE;
        } else {
            $info->success = TRUE;
            $info->url = $product->Url;
            $info->name = $product->Name;
            $info->price = $product->Price;
            $info->image = $product->Image;
            $info->shipFee = (float)$product->ShipFee;
            $info->sku = $product->Sku;
            $info->hasSkus = $product->HasSkus;
            $info->quantity = $product->Quantity;
            $info->shopId = $product->ShopId;
            $info->priceError = $product->PromotionError == TRUE?TRUE:FALSE;
            $skus = array();
            foreach ($product->getSkus() as $sku) {
                $item = new stdClass();
                $item->properties = $sku->Properties;
                $item->price = $sku->Price;
                $item->quantity = $sku->Quantity;
                $item->skuNo = $sku->SkuNo;
                array_unshift($skus, $item);
            }
            $info->skus = $skus;
            $info->option = $product->getOption();
        }
        $this->view->info = $info;
    }
	
	public function getinfonewAction() {  
        $url = $this->getRequest()->getParam('url');
        $url = trim($url);
        $reader = Uuch_Reader_ProductReader::Create($url);
        $result = $reader->getInfoForNew($url);
		$product = $result['product'];
        $info = new stdClass();

        if ($product == NULL) {
            $info->success = FALSE;
        } else {
            $info->success = TRUE;
            $info->url = $product->Url;
            $info->name = $product->Name;
            $info->price = $product->Price;
            $info->image = $product->Image;
            $info->shipFee = (float)$product->ShipFee;
            $info->sku = $product->Sku;
            $info->hasSkus = $product->HasSkus;
            $info->quantity = $product->Quantity;
            $info->shopId = $product->ShopId;
            $info->priceError = $product->PromotionError == TRUE?TRUE:FALSE;
            $skus = array();
            foreach ($product->getSkus() as $sku) {
                $item = new stdClass();
                $item->properties = $sku->Properties;
                $item->price = $sku->Price;
                $item->quantity = $sku->Quantity;
                $item->skuNo = $sku->SkuNo;
                array_unshift($skus, $item);
            }
            $info->skus = $skus;
            $info->option = $product->getOption();
        }
		$info->status = $info->success ? 'success' : 'error';
		$info->shopName = $result['shopName'];
		$info->shopType = $result['siteName'];
		$info->sellerShopUrl = $result['shopUrl'];
		$info->shopUrl = $result['siteUrl'];
		ob_end_clean();
        echo json_encode($info);
		exit;
    }		

    public function changeitemAction() {
        $request = $this->getRequest();
        $userId = $this->currentUser()->Id;
        $itemid = $request->getParam('itemid');
        $quantity = $request->getParam('quantity');
        $comment = $request->getParam('comment');
        $selected = $request->getParam('selected');
        $item = Application_Model_CartItem::load($itemid);
        $item->Quantity = $quantity;
        $item->Comment = $comment;
        $item->IsSelected = $selected;
        $item->save();
        //修改记录到临时表
        Application_Model_TemporaryCart::addTemporaryLog($item->cartId, $item->Id, $item->ProductName, $item->quantity, Application_Model_TemporaryCart::Type_Edit, $userId);
        $this->json(TRUE);
    }

    public function testAction() {
        $reader = new Uuch_Reader_TaobaoReader();
        $product = $reader->getInfo('http://detail.tmall.com/item.htm?spm=a230r.1.14.14.Dd4zRN&id=17200418412&ad_id=&am_id=&cm_id=140105335569ed55e27b&pm_id=');
        $this->view->product = $product;
        $this->disableLayout();
    }
    
    public function alibabaAction(){
        $reader = new Uuch_Reader_CommonReader();
        $this->json($reader->getInfo('http://detail.1688.com/offer/1233067542.html'));
    }
    
    public function urlAction(){
        $this->view->url = $this->_getParam('url');
        $this->view->img = $this->getHeadPic();
        $this->disableLayout();
    }
    
    public function getHeadPic() {
        if ($this->currentUser()->pic) {
            $userid = str_pad($this->currentUser()->id, 9, '0', STR_PAD_LEFT);
            if(file_exists("http://www.uuch.com/pub/static/frontend/Uuch/basic/zh_CN/photo/".substr($userid, 0, 3) . '/' . substr($userid, 3, 2) . '/' . substr($userid, 5, 2) . '/' . $this->currentUser()->pic)){
              return "http://www.uuch.com/pub/static/frontend/Uuch/basic/zh_CN/photo/".substr($userid, 0, 3) . '/' . substr($userid, 3, 2) . '/' . substr($userid, 5, 2) . '/' . $this->currentUser()->pic;
            } else {
                return "http://old.uuch.com/data/avatar/".substr($userid, 0, 3) . '/' . substr($userid, 3, 2) . '/' . substr($userid, 5, 2) . '/' . $this->currentUser()->pic;
            }
        } else {
            return "http://www.uuch.com/pub/static/frontend/Uuch/basic/zh_CN/photo/photo.png";
        }
    }


    public function testinfoAction(){
        $url = 'http://item.jd.com/1020863761.html';
        $reader = Uuch_Reader_ProductReader::Create($url);        
        $product = $reader->getInfo($url);
        $this->json($product);        
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';      
    }
    
    public function infoAction()
    {
        //35899057017  ---- 23464084151  17200418412
        $id = "23464084151";
        $url = "http://mdskip.taobao.com/core/initItemDetail.htm?itemId=".$id;
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        $data = array ( 
                "Referer: http://detail.tmall.com/item.htm?id=".$id,
            );
        $ch = curl_init($url); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, $data); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $html = curl_exec($ch);
        curl_close($ch);
        $htmlA =iconv("GB2312", 'UTF-8', trim($html));
//        echo "<br><br><br><br>";
        if(preg_match('/\w:/', $htmlA)){
            $htmlA = preg_replace('/{(\w+):/is', '{"$1":', $htmlA);
            $htmlA = preg_replace('/,(\w+):/is', ',"$1":', $htmlA);
        }
        $htmlB = json_decode($htmlA);
        $minPrice = 99999;
        var_dump($htmlB);exit;
        foreach ($htmlB->defaultModel->itemPriceResultDO->priceInfo as $key => $value) {
//            if($key == "def"){
//                echo $value->price."<br>";
//            }
            foreach ($value->promotionList as $key1 => $value1) {
                    $minPrice = $value1->price<=$minPrice?$value1->price:$minPrice;
                
            }
        }
        echo $minPrice;
        exit;
    }
}

